/* globals app, Split, ace */
app.setup = {};

app.setup.splitPanes = function() {
	app.splits = {};
	var vw = window.innerWidth;
	var demoWidth = Math.ceil(500 * 100 / vw);

	var taskBtn = document.querySelector("#task-button");
	var previewBtn = document.querySelector("#preview-button");
	var themeBtn = document.querySelector("#theme-button");
	var index = 0;
	var index2 = 0;

	taskBtn.addEventListener("click", function() {
		index++;
		app.util.resize.chgTask(index % 2 == 0);
	});
	previewBtn.addEventListener("click", function() {
		index2++;
		app.util.resize.chgPreview(index2 % 2 == 0);
	});
	themeBtn.addEventListener("click", function() {
		app.services.toggleTheme();
	});

	if (!app.config.compact) { // Full View
		app.splits.main = Split(['#leftPane', '#rightPane', '#previewPane'], {
			gutterSize: 5,
			sizes: [demoWidth, 80 - demoWidth, 20],
			minSize: [0, 0, 0],
			cursor: 'col-resize',
			onDrag: app.util.resize.editorResize
		});
		frameSize = app.util.getLocalSize();
		if (frameSize) {
			frameSizeNum = (frameSize.split(',')).map(Number);
			app.splits.main.setSizes(frameSizeNum);
		}
	} else { // Compact View
		app.config.showDocs = app.util.getParam('docs') !== 'false';
		if (app.config.showDocs) {
			app.splits.main = Split(['#leftPane', '#centerPane', '#rightPane'], {
				gutterSize: 10,
				sizes: [25, demoWidth, 100 - 25 - demoWidth],
				minSize: [1, 301, 0],
				cursor: 'col-resize',
				onDrag: app.util.resize.editorResize
			});
		} else {
			document.querySelector('#leftPane').style.display = 'none';
			app.splits.main = Split(['#centerPane', '#rightPane'], {
				gutterSize: 10,
				sizes: [demoWidth, 100 - demoWidth],
				minSize: [301, 0],
				cursor: 'col-resize',
				onDrag: app.util.resize.editorResize
			});
		}
	};

	app.util.saveSize();

	app.splits.editors = Split(['#rightTopPane', '#rightMiddlePane', '#rightBottomPane'], {
		direction: 'vertical',
		gutterSize: 5,
		sizes: [33, 33, 34],
		minSize: 0,
		cursor: 'row-resize',
		onDrag: app.util.resize.editorResize
	});

	var rememberDrag = function(event) {
		app.config.autoHideHTMLPane = false;
		event.target.removeEventListener('click', rememberDrag);
	};

	document.querySelector('#rightPane .gutter-vertical').addEventListener('click', rememberDrag);
	app.util.saveSize();
};

app.setup.editor = function(id, language) {
	ace.require("ace/ext/language_tools");
	var editor = ace.edit(id);
	var beautify = ace.require("ace/ext/beautify");
	editor.setTheme('ace/theme/' + (document.body.classList.contains('dark-skin') ? 'monokai' : 'chrome'));
	editor.session.setMode("ace/mode/" + language);
	editor.session.setTabSize(2);
	editor.session.setUseSoftTabs(true);
	editor.renderer.setShowGutter(!!window.Split);
	editor.container.style.lineHeight = 1.3;
	editor.$blockScrolling = Infinity;
	editor.setOptions({
		fontSize: '14px',
		fontFamily: 'Lucida Sans Typewriter',
		enableBasicAutocompletion: true,
		enableSnippets: true,
		enableLiveAutocompletion: true,
		showPrintMargin: false,
		enableEmmet: true
	});

	editor.commands.addCommand({
		name: 'beautify',
		bindKey: {
			win: 'Ctrl-S',
			mac: 'Command-S'
		},
		exec: function(editor,language) {
			editor.session.setMode("ace/mode/" + language);
			beautify.beautify(editor.session);
			app.services.runProject();
		}
	});
	
	editor.commands.addCommand({
		name: 'selectAll',
		bindKey: {
			win: 'Ctrl-A',
			mac: 'Command-A'
		},
		exec: function(editor) {
			editor.selectAll();
			beautify.beautify(editor.session);
			
		}
	});
	
	// editor.session.on("change",function(){
	// 	setTimeout(function(){
	// 		//editor.execCommand("beautify");
	// 	},5000);
	// });

	editor.session.on("changeAnnotation", function() {
		var annotations = editor.session.getAnnotations() || [];
		var len = annotations.length;
		var i = annotations.length;
		while (i--) {
			var a = annotations[i].text;
			if ((/doctype first\. Expected/).test(a) ||
				(/Unexpected End of file\. Expected/).test(a)) {
				annotations.splice(i, 1);
			}
		}
		if (len > annotations.length) {
			editor.session.setAnnotations(annotations);
		}
	});

	return editor;
};

app.setup.pagesCounter = function() {
	document.getElementById('pages-previous').onclick = function() {
		if (app.tutorial && app.tutorial.pageIndex > 0) {
			app.tutorial.pageIndex--;
			document.getElementById('pages-current').innerHTML = app.tutorial.pageIndex + 1;
			app.services.updateTutorialPage();
		}
	};

	document.getElementById('pages-next').onclick = function() {
		if (app.tutorial && app.tutorial.pageIndex < app.tutorial.pages.length - 1) {
			app.tutorial.pageIndex++;
			document.getElementById('pages-current').innerHTML = app.tutorial.pageIndex + 1;
			app.services.updateTutorialPage();
		}
	};
};

app.setup.tabView = function() {
	var activeTabIndex = app.util.getParam('tab-active');
	var visibleTabs = app.util.getParam('tab-visibility');

	if (activeTabIndex) {
		var activeTab = document.querySelector('#tab-' + activeTabIndex);
		if (activeTab) {
			activeTab.checked = true;
		}
	}

	if (visibleTabs) {
		for (var i = 1; i <= 4; i++) {
			document.querySelector('#tab-' + i).parentElement.children[1].style.display = (+visibleTabs[i - 1]) ?
				'' : 'none';
		}
	}

	// var mainViewLink = document.querySelector('.main-view-link a');
	// mainViewLink.setAttribute('href', window.location.href.replace('/tabs.html', '/index.html'));
};

app.setup.toolbar = function() {
	//document.querySelector('#codepen-form').onsubmit = app.services.codepenSubmit;
	//document.querySelector('#modify-button').onclick = app.services.modifySource;
	//document.querySelector('#issue-button').onclick = app.services.reportIssue;
};

app.setup.modules = function() {
	var frameworkItems = Array.prototype.slice.call(document.body.querySelectorAll('.framework-item'));

	frameworkItems.forEach(function(frameworkItem) {
		var framework = frameworkItem.querySelector('label').getAttribute('framework');
		var moduleList = frameworkItem.querySelector('.module-list');

		if (app.modules.hasOwnProperty(framework)) {
			Object.keys(app.modules[framework]).forEach(function(category, index) {
				var id = `c-${framework}-${app.util.parseId(category)}`;
				var categoryItem = document.createElement('li');
				categoryItem.classList.add('category-item');

				categoryItem.innerHTML =
					`
          <input type="checkbox" id="${id}" ${index === 0 ? 'checked' : ''}>
          <label for="${id}" category="${category}"></label>
        `;

				var listElement = document.createElement('ul');

				Object.keys(app.modules[framework][category]).forEach(function(module) {
					var id =
						`r-${framework}-${app.util.parseId(category)}-${app.util.parseId(module)}`;
					var moduleItem = document.createElement('li');
					moduleItem.classList.add('module-item');
					var itemContent = app.modules[framework][category][module].split('|');
					var itemDescription = itemContent[0];
					var itemKeywords = (app.modulesDefaultKeywords.hasOwnProperty(module) ?
						app.modulesDefaultKeywords[module] :
						'').concat(itemContent[1] || '');
					moduleItem.innerHTML =
						`
            <input type="radio" name="select-item" id="${id}">
            <label for="${id}" module="${module}" desc="${itemDescription}" keywords="${itemKeywords}"></label>
          `;
					listElement.appendChild(moduleItem)
				});

				categoryItem.appendChild(listElement);
				moduleList.appendChild(categoryItem);
			});

			if (moduleList.querySelectorAll('li').length) {
				var extraInfo = document.createElement('li');
				extraInfo.classList.add('category-item');
				extraInfo.innerHTML =
					`
          <a href="https://onsen.io/v2/docs/${framework === 'vanilla' ? 'js' : framework}.html">Further Reading</a>
        `;
				moduleList.appendChild(extraInfo);
			} else {
				var comingSoon = document.createElement('div');
				comingSoon.classList.add('coming-soon');
				comingSoon.innerHTML = 'Coming soon ™';
				moduleList.appendChild(comingSoon);
			}
		}

		document.body.querySelector('#modules').onchange = function(event) {
			if (event.target.name === 'select-item') {
				var el = event.target;
				var framework = el.parentElement.parentElement.parentElement.parentElement
					.previousElementSibling.getAttribute(
						'framework');
				var category = el.parentElement.parentElement.previousElementSibling.getAttribute(
					'category');
				var module = el.nextElementSibling.getAttribute('module');

				app.services.changeModule(framework, category, module).then(app.services.runProject);
				app.services.updateSelectedItem(framework, module);
				document.body.querySelector('#modules input').checked = false;
			}
		};

		document.body.querySelector('#search-input').onclick = function(event) {
			event.preventDefault();
		};

		document.body.querySelector('#search-input').oninput = function(event) {
			var words = event.target.value.split(/\s+/);
			var items = [];

			words.forEach(function(word) {
				if (word) {
					var query = '#modules .module-item label';

					['keywords', 'module', 'desc'].forEach(function(attr) {
						query += `:not([${attr}*="${word}" i])`;
					});

					items = items.concat(Array.prototype.slice.call(document.querySelectorAll(
						query)));
				}
			});

			Array.prototype.forEach.call(document.querySelectorAll('#modules .module-item.filtered'),
				function(item) {
					item.classList.remove('filtered');
				});

			if (items.length > 0) {
				items.forEach(function(item) {
					item.parentElement.classList.add('filtered');
				});
			}
		};
	});
};

app.setup.displayTitle = function() {
	setTimeout(function() {
		document.querySelector('.full').classList.add("hide");
	}, 2000);
}
